import { StyleSheet, Text, View, Image, Pressable } from 'react-native';
import React, { useEffect, useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import Icon from 'react-native-vector-icons/Ionicons';
import { useNavigation } from '@react-navigation/native';
import dayjs from 'dayjs';
import { px2dp, scale } from '~/utils/px2dp';
import { calcStepData } from '~/utils/helpers';
import { observer, deviceStore, userStore } from '~/store';
import { getStepData, getHeartRateToday, getBloodPressureData } from '~/api/deviceToolsApi';
import { applyBloodDevice } from '~/utils/deviceMenues';

interface Props {
    selectDate: string;
}
export default observer((props: Props) => {
    const navigation: any = useNavigation();
    const { t } = useTranslation();
    const { selectDate } = props;
    const { userBindDeviceData, autoConnectDeviceSn } = userStore;
    // 获取步数
    const [stepInfo, setStepInfo] = useState({
        calories: '',
        distance: '',
        goal: 3500,
        goalCalories: '',
        goalDistance: '',
        steps: '',
        time: { hours: 0, minutes: 0 },
    });
    const { device, connectDeviceInfo } = deviceStore;
    const deviceInfo = useMemo(() => {
        let res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
        if (deviceStore.device?.connectedDeviceStatus == 1) {
            res = userBindDeviceData.find((item) => item.device_sn == device?.connectDevice?.device_sn);
        } else {
            if (autoConnectDeviceSn) {
                res = userBindDeviceData.find((item) => item.device_sn == autoConnectDeviceSn);
            } else {
                res = userBindDeviceData[0];
            }
        }
        return res;
    }, [
        userBindDeviceData,
        autoConnectDeviceSn,
        deviceStore.device?.connectedDeviceStatus,
        device?.connectDevice?.device_sn,
    ]);
    const getDayStep = (timestamp = dayjs(selectDate).valueOf()) => {
        getStepData({
            deviceId: deviceInfo?.device_id,
            type: 1,
            device_sn: deviceInfo?.device_sn,
            startTime: timestamp,
            endTime: timestamp,
        }).then((res) => {
            if (res.code == 200) {
                const { myGoal, mySteps } = res?.returnData?.userTodayData;
                const result = calcStepData(myGoal > 0 ? myGoal : 2000, mySteps);
                setStepInfo(result);
            }
        });
    };
    // 获取心率数据
    const [heartData, setHeartData] = useState<any>({
        last: { time: '', value: 0 },
        prev: { time: '', value: 0 },
    });
    function indexToTime(index) {
        const minutes = index * 15;
        const h = String(Math.floor(minutes / 60)).padStart(2, '0');
        const m = String(minutes % 60).padStart(2, '0');
        return `${h}:${m}`;
    }
    const getHeartToday = () => {
        getHeartRateToday({
            deviceId: deviceInfo?.device_id,
            device_sn: deviceInfo?.device_sn,
        }).then((res) => {
            const result = res.returnData;
            if (Array.isArray(result)) {
                if (result.length === 0) {
                }
            } else if (result && typeof result === 'object') {
                const data = Object.entries(result).map(([index, value]) => {
                    return { time: indexToTime(Number(index)), value };
                });
                if (data.length > 0) {
                    const lastTwo = data.slice(-2); // 取最后两条
                    setHeartData({
                        prev: lastTwo[0], // 倒数第二条
                        last: lastTwo[1], // 最后一条
                    });
                }
            } else {
            }
        });
    };
    // 获取血压数据
    const [bloodData, setBloodData] = useState({ diastole: 0, heartRate: 0, systolic: 0, time: '', status: 2 });
    const getBloodData = () => {
        const formattedDate = dayjs().format('YYYY/M/D');
        getBloodPressureData({
            device_sn: deviceInfo?.device_sn,
            type: 'day',
            day_date: formattedDate,
        }).then((res) => {
            if (Array.isArray(res.data) && res.data.length == 0) {
                return;
            }
            const { diastole, heartRate, systolic, time } = res.data;
            const info = {
                diastole: diastole.at(-1), // 舒张压
                heartRate: heartRate.at(-1), // 心率数据
                systolic: systolic.at(-1), // 收缩压
                time: time.at(-1),
            };
            let status = 2;
            if (info.systolic < 90 || info.diastole < 60) {
                status = 1;
            } else if (info.systolic < 120 && info.diastole < 80) {
                status = 2;
            } else if (info.systolic < 130 && info.diastole < 80) {
                status = 3;
            } else if (info.systolic < 140 || info.diastole < 90) {
                status = 4;
            } else if (info.systolic < 160 || info.diastole < 100) {
                status = 5;
            } else {
                status = 6;
            }
            setBloodData({ ...info, status });
        });
    };
    const getData = () => {
        getDayStep();
        getHeartToday();
        getBloodData();
    };
    const goLaserDetailes = () => {
        if (userStore.userBindDeviceData.length == 0) {
            Toast.show({ content: t('HomeScreen.t17') });
            return;
        }
        navigation.navigate('LaserCycle', {
            type: 'ble',
            subDevice_sn: deviceInfo.device_sn,
            device_code: deviceInfo.device_code,
        });
    };
    const goMenue = (params) => {
        if (userStore.userBindDeviceData.length == 0) {
            Toast.show({ content: t('HomeScreen.t17') });
            return;
        }
        navigation.navigate('Main', {
            screen: 'Health',
            params,
        });
    };
    useEffect(() => {
        getData();
    }, [deviceInfo]);

    return (
        <View style={styles.dayContent}>
            <Text style={styles.title}>{t('DeviceData.t1')}</Text>
            {device.connectedDeviceStatus == 1 && (
                <Pressable style={[styles.row, styles.between, styles.card]} onPress={goLaserDetailes}>
                    <View style={styles.row}>
                        <Image source={require('~/assets/home/laser.png')} resizeMode="contain" style={styles.icons} />
                        <Text style={styles.t3}>{t('DeviceData.t2')}</Text>
                    </View>
                    <Icon name="chevron-forward-outline" size={px2dp(40)} color={'#a4a4a4'}></Icon>
                </Pressable>
            )}
            {device.connectedDeviceStatus == 1 && (
                <>
                    {applyBloodDevice.indexOf(deviceInfo?.device_code) == -1 ? (
                        <Pressable
                            style={[styles.row, styles.between, styles.card]}
                            onPress={() =>
                                goMenue({
                                    id: 2,
                                    title: t('HealthScreen.t1'),
                                    icon: require('~/assets/home/heart.png'),
                                })
                            }>
                            <View style={styles.row}>
                                <Image
                                    source={require('~/assets/home/heart.png')}
                                    resizeMode="contain"
                                    style={styles.icons}
                                />
                                <Text style={styles.t1}>{t('DeviceData.t4')}(BPM)</Text>
                            </View>
                            <View style={styles.row}>
                                <View style={{ marginRight: px2dp(20) }}>
                                    <Text style={styles.t2}>{heartData?.prev?.value || '-'}</Text>
                                    <Text style={styles.t3}>{heartData?.last?.value || '-'}</Text>
                                </View>
                                <Icon
                                    name={heartData?.prev?.value > heartData?.last?.value ? 'caret-up' : 'caret-down'}
                                    size={px2dp(40)}
                                    color={
                                        heartData?.prev?.value > heartData?.last?.value ? '#1DCE87' : '#E8CE35'
                                    }></Icon>
                            </View>
                        </Pressable>
                    ) : (
                        <Pressable
                            style={[styles.row, styles.between, styles.card]}
                            onPress={() =>
                                goMenue({
                                    id: 3,
                                    title: t('HealthScreen.t2'),
                                    icon: require('~/assets/home/blood.png'),
                                })
                            }>
                            <View style={styles.row}>
                                <Image
                                    source={require('~/assets/home/heart.png')}
                                    resizeMode="contain"
                                    style={styles.icons}
                                />
                                <Text style={styles.t1}>{t('DeviceData.t4')}(BPM)</Text>
                            </View>
                            <Text style={styles.t2}>{bloodData?.heartRate || '-'}</Text>
                        </Pressable>
                    )}
                </>
            )}
            {applyBloodDevice.indexOf(deviceInfo?.device_code) !== -1 && device.connectedDeviceStatus == 1 && (
                <Pressable
                    style={[styles.row, styles.between, styles.card]}
                    onPress={() =>
                        goMenue({
                            id: 3,
                            title: t('HealthScreen.t2'),
                            icon: require('~/assets/home/blood.png'),
                        })
                    }>
                    <View style={styles.row}>
                        <Image source={require('~/assets/home/blood.png')} resizeMode="contain" style={styles.icons} />
                        <Text style={styles.t1}>{t('DeviceData.t5')}(MMHG)</Text>
                    </View>
                    <Text style={styles.t2}>
                        {bloodData.diastole || '-'}
                        <Text style={styles.t3}> / </Text>
                        {bloodData.systolic || '-'}
                    </Text>
                </Pressable>
            )}

            <Pressable
                style={[styles.row, styles.between, styles.card]}
                onPress={() =>
                    goMenue({
                        id: 1,
                        title: t('HealthScreen.t3'),
                        icon: require('~/assets/home/step.png'),
                    })
                }>
                <View style={styles.row}>
                    <Image source={require('~/assets/home/step.png')} resizeMode="contain" style={styles.icons} />
                    <Text style={styles.t1}>{t('DeviceData.t6')}</Text>
                </View>
                <Text style={styles.t2}>{stepInfo.steps}</Text>
            </Pressable>
            <Pressable
                style={[styles.row, styles.between, styles.card]}
                onPress={() =>
                    goMenue({
                        id: 1,
                        title: t('HealthScreen.t3'),
                        icon: require('~/assets/home/step.png'),
                    })
                }>
                <View style={styles.row}>
                    <Image source={require('~/assets/home/calorie.png')} resizeMode="contain" style={styles.icons} />
                    <Text style={styles.t1}>{t('DeviceData.t7')}</Text>
                </View>
                <Text style={styles.t2}>
                    {stepInfo.calories}
                    <Text style={styles.t4}>kcal</Text>
                </Text>
            </Pressable>
            <Pressable
                style={[styles.row, styles.between, styles.card]}
                onPress={() =>
                    goMenue({
                        id: 1,
                        title: t('HealthScreen.t3'),
                        icon: require('~/assets/home/step.png'),
                    })
                }>
                <View style={styles.row}>
                    <Image source={require('~/assets/home/distance.png')} resizeMode="contain" style={styles.icons} />
                    <Text style={styles.t1}>{t('DeviceData.t8')}</Text>
                </View>
                <Text style={styles.t2}>
                    {stepInfo.distance} <Text style={styles.t4}>km</Text>
                </Text>
            </Pressable>
            <Pressable
                style={[styles.row, styles.between, styles.card]}
                onPress={() =>
                    goMenue({
                        id: 1,
                        title: t('HealthScreen.t3'),
                        icon: require('~/assets/home/step.png'),
                    })
                }>
                <View style={styles.row}>
                    <Image source={require('~/assets/home/time.png')} resizeMode="contain" style={styles.icons} />
                    <Text style={styles.t1}>{t('DeviceData.t9')}</Text>
                </View>
                <View style={styles.row}>
                    <Text style={[styles.t2, { marginRight: px2dp(12) }]}>{stepInfo.time.hours}</Text>
                    <Text style={styles.t4}>h</Text>
                    <Text style={[styles.t2, { marginHorizontal: px2dp(12) }]}>{stepInfo.time.minutes}</Text>
                    <Text style={styles.t4}>m</Text>
                </View>
            </Pressable>
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    between: {
        justifyContent: 'space-between',
    },
    title: {
        color: '#fff',
        fontSize: scale(40),
        fontWeight: 'bold',
    },
    dayContent: {
        marginTop: px2dp(64),
    },
    card: {
        borderWidth: 1,
        borderColor: 'rgba(255, 255, 255, 0.12)',
        padding: px2dp(24),
        marginTop: px2dp(32),
        borderRadius: px2dp(24),
    },
    icons: {
        width: px2dp(50),
        height: px2dp(50),
        marginRight: px2dp(12),
    },
    t1: {
        color: '#D4D4D4',
        fontSize: scale(28),
    },
    t2: {
        color: '#fff',
        fontSize: scale(50),
        fontWeight: 'bold',
        textAlign: 'center',
    },
    t3: {
        color: '#D4D4D4',
        fontSize: scale(28),
        textAlign: 'center',
    },
    t4: {
        color: '#a4a4a4',
        fontSize: scale(26),
    },
    time: {
        color: '#fff',
        fontSize: scale(26),
        fontWeight: 'bold',
    },
});
